package com.by.controller;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.by.bean.Product;
import com.by.mapper.ProductMapper;
import com.by.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
public class ExcelListener implements ReadListener<Product> {
    /**
     * 每隔10条存储数据库
     */
    private  static final int BATCH_COUNT=10;
    /**
     * 缓存的数据
     */
    private List<Product> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private ProductService productService;
   public ExcelListener(ProductService productService){
       this.productService=productService;
   }
    @Override
    public void invoke(Product product, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(product));
        cachedDataList.add(product);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }
    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param Context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext Context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 存储到数据库
     */
    private void saveData(){
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        productService.save(cachedDataList);
        log.info("存储数据库成功！");
    }
}
